// 引入接口文件
import { queryAllAddress, houseListGet, counselorServ, uuseeListServ, createLive, updateLive, detailServ, livePublish, liveCancelPublish, searchAnchor } from './liveDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import config from 'config/config';
import { download } from 'utils/util'
import { makeAddress } from "utils/util"

// 初始默认状态
const defultState = {
    loading: false,
    btnLoading: false,
    actionType: '',
    detail: {
        published: 0,
        linkUrl: '',
        liveBroadcastRelats: {}
    },
    isDisabled: false, //表单控件 是否可操作做
    areaList: [], //省市区列表
    estateList: [], //市对应的楼盘项目
    imgModal: {
        visible: false,
        srcs: [],
    },
    searchBox: {
        visible: false
    },
    selectRows: {

    },
    confirmRows: {

    },
    consultantList: [],
    detailData: {},
    uuseeList: [], //平台列表
    counselorList: [],
    preVideoUrlArr: [],
    recordVideoUrlArr: [],
    liveListDemo: ['https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/liveListDemo01.jpg'],
    iconList: [
        'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/live/icon-activity1.png',
        'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/live/icon-activity2.png',
        'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/live/icon-activity3.png',
        'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/live/icon-activity4.png'
    ],
    biz: {
        1: {
            queryForm: {},
            rowSelection_type: 'radio',
            selectedRowKeys: []
        },
        2: {
            queryForm: {},
            rowSelection_type: 'radio',
            selectedRowKeys: []
        },
        3: {
            queryForm: {},
            rowSelection_type: 'radio',
            selectedRowKeys: []
        }
    },
    relatItem: {
        1: 'ACTIVITY',
        2: 'SELFSERVICE',
        3: 'ONLINEOPEN'
    },
    activityModalObj: {
        visible: false,
        activityType: 1
    },
    currentItem: [],
    // relatType:'',// 关联对象类型 ACTIVITY活动 GAME游戏 COUPONS优惠卷，当 type为activity时才有relatItem、icon_url
    // 		relatItem:'', // 关联对象细项 ACTIVITY活动 SELFSERVICE自助购房 ONLINEOPEN在线开盘
    // 		iconUrl:'', // 活动图标
    // 		relatId:'',// 关联对象ID
    // 		title:'',// 标题
    // 		url:'',// 链接
    // 		start_time:'',// 开始时间
    // 		end_time:''// 结束时间
    liveBroadcastRelats: {
        ACTIVITY: [],
        GAME: [],
        COUPONS: [],
        SECKILL: [],
        BID: []
    },
    gameObj: {
        visible: false
    },
    gameBiz: {
        queryForm: {},
        rowSelection_type: 'checkbox',
        selectedRowKeys: []
    },
    killObj: {
        visible: false
    },
    killBiz: {
        queryForm: {},
        rowSelection_type: 'checkbox',
        selectedRowKeys: []
    },
    couponObj: {
        visible: false
    },
    couponBiz: {
        queryForm: {},
        rowSelection_type: 'radio',
        selectedRowKeys: []
    }

}



// 声明module
const tmpModule = {
    // 默认状态
    state: cloneDeep(defultState),
    // 入口函数(先执行)
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                    console.log(query)
                    let { actionType, id } = query
                    // 页面路由匹配时执行
                    if ('' + tmpModule.pathname === '' + pathname) {
                        if (actionType != 'add') {
                            dispatch({ type: 'getDetail', payload: { id, actionType } });
                        }
                        dispatch({ type: 'updateStore', payload: cloneDeep(defultState) })
                        dispatch({ type: 'updateStore', payload: { actionType } });

                        dispatch({ type: 'getAreaList', payload: {} });
                        dispatch({ type: 'getUuseeList', payload: {} });
                        // dispatch({ type: 'searchAnchor', payload: {} });
                    } // end if
                }) // end listen
        },
    },

    // 方法列表
    effects: {
        * searchAnchor({ payload }, { put, call, select }) {
            try {
                console.log('payload', payload)
                const { success, msg, data, pageNo, pageSize, total } = yield call(searchAnchor, {...payload });
                if (success) {
                    let consultantList = []
                    consultantList = data
                    let detailData = defultState.detailData
                    detailData.pageNo = pageNo
                    detailData.pageSize = pageSize
                    detailData.total = total
                    yield put({ type: 'updateStore', payload: { consultantList, detailData } })
                }
            } catch (e) {
                console.log(e)
            }
        },
        * publish({ payload }, { put, call, select }) {
            try {
                console.log('payload', payload)
                let { actionType, detail } = yield select(state => state[tmpModule.namespace])

                let { success, msg } = yield call(livePublish, {...payload });

                if (success) {
                    message.success('发布成功')
                    hashHistory.push({
                        pathname: '/home/infoAdmin/liveList'
                    })
                } else {
                    if (actionType == 'add') {
                        msg = `该直播信息已保存成功。发布失败，失败原因：${msg}`
                            // message.error(msg)
                        message.error(msg)
                        yield put({ type: 'getDetail', payload: { id: payload.id } })
                        yield put({ type: 'updateStore', payload: { actionType: 'edit' } })


                    } else {
                        message.error(msg)

                    }
                }
            } catch (e) {
                console.log(e)
            }
        },
        * cancelPublish({ payload }, { put, call, select }) {
            try {
                const { success, msg } = yield call(liveCancelPublish, {...payload })

                if (success) {

                    message.success('取消成功')
                        // hashHistory.push({
                        // 	pathname:'/home/infoAdmin/liveList'
                        // })
                    yield put({ type: 'getDetail', payload: { id: payload.id } })


                } else {
                    message.error(msg)
                }
            } catch (e) {}
        },
        * getAreaList({ payload }, { put, call, select }) {
            try {
                const { success, data } = yield call(queryAllAddress, {})
                if (success) {
                    //todo: 接口格式调整后删除
                    let areaList = []
                    let arr = [data[0]]
                    let attr = [data[data.length - 1]]
                    data[0] = {
                        label: "北京",
                        value: "110100",
                        children: arr
                    }
                    data[data.length - 1] = {
                            label: "澳门",
                            value: "820000",
                            children: attr
                        }
                        //console.log(data,"data")
                        //去掉第三级，
                    areaList = makeAddress(data, 2, false)
                    yield put({ type: 'updateStore', payload: { areaList } })

                }
            } catch (e) {}
        },
        // 获取户型项目
        * getHouseArea({ payload }, { put, call, select }) {
            let params = cloneDeep(payload)
            params.pageNo = 1
            params.pageSize = 999999
            try {
                const { success, rows } = yield call(houseListGet, params)
                if (success) {
                    yield put({ type: 'updateStore', payload: { estateList: rows || [] } })
                }
            } catch (e) {
                console.log(e)
            }
        },

        //根据项目id查询置业顾问
        * getCounselor({ payload }, { put, call, select }) {
            try {
                let { success, rows } = yield call(counselorServ, payload.projectId)
                if (success) {
                    yield put({ type: 'updateStore', payload: { counselorList: rows } });
                }
            } catch (e) {}
        },
        // 直播平台列表
        * getUuseeList({ payload }, { put, call, select }) {
            try {
                let { success, rows } = yield call(uuseeListServ, { pageSize: 99999 })
                if (success) {
                    yield put({ type: 'updateStore', payload: { uuseeList: rows } });
                }
            } catch (e) {}
        },
        //获取直播详情
        * getDetail({ payload }, { put, call, select }) {
            try {
                let { liveBroadcastRelats, actionType } = yield select(state => state[tmpModule.namespace])
                let { id } = payload
                let { success, data } = yield call(detailServ, { id })
                if (success) {
                    console.log(data);
                    data.city = data.cityCode
                    data.province = data.provinceCode
                    let videoObj1 = [{
                        name: data.preVideoUrl,
                        value: data.preVideoUrl
                    }]
                    let videoObj2 = [{
                        name: data.recordVideoUrl,
                        value: data.recordVideoUrl
                    }]
                    yield put({
                        type: 'updateStore',
                        payload: {
                            detail: {
                                ...data,
                                anchorMobile:data.counselorPhone,
                                anchorName:data.counselorName
                            },
                            preVideoUrlArr: videoObj1,
                            recordVideoUrlArr: videoObj2,
                            confirmRows: {        
                                name: data.counselorName,
                                mobile: data.counselorPhone
                            },
                            liveBroadcastRelats: data && data.liveBroadcastRelats ? data.liveBroadcastRelats : liveBroadcastRelats
                        }
                    });

                    yield put({ type: 'handleDisabled', payload: { actionType: payload.actionType || actionType, published: data.published } });
                    yield put({ type: 'getCounselor', payload: { projectId: data.productId } });

                }
            } catch (e) {}
        },
        * saveLive({ payload }, { put, call, select }) {
            try {
                let { detail, actionType, liveBroadcastRelats } = yield select(state => state[tmpModule.namespace])
                    // let {ACTIVITY={},GAME={},COUPONS={}} = liveBroadcastRelats
                if (liveBroadcastRelats.SECKILL && liveBroadcastRelats.SECKILL.length) {
                    if (new Date(liveBroadcastRelats.SECKILL[0].startTime).getTime() < new Date(detail.effectiveStartTime).getTime() || new Date(liveBroadcastRelats.SECKILL[0].endTime).getTime() > new Date(detail.effectiveEndTime).getTime()) {
                        message.error('秒杀活动时间一定要在直播时间段范围内');
                    }
                }
                if (liveBroadcastRelats.BID && liveBroadcastRelats.BID.length) {
                    if (new Date(liveBroadcastRelats.BID[0].startTime).getTime() < new Date(detail.effectiveStartTime).getTime() || new Date(liveBroadcastRelats.BID[0].endTime).getTime() > new Date(detail.effectiveEndTime).getTime()) {
                        message.error('竞拍活动时间一定要在直播时间段范围内');
                        return false;
                    }
                }
                if (detail.broadcastMode == 2 && (!detail.recordVideoUrl || detail.recordVideoUrl == "" || detail.recordVideoUrl == null)) {
                    message.error('请上传直播视频');
                    return false;
                }
                detail.liveBroadcastRelats = liveBroadcastRelats
                let liveServ = actionType == 'add' ? createLive : updateLive;
                console.log(detail);
                let { success, data } = yield call(liveServ, detail)
                if (success) {
                    let username = localStorage.getItem('username')

                    if (payload.type == 'publish') {
                        yield put({ type: 'publish', payload: { id: data.id, updatePerson: username } });
                    } else {
                        message.success('保存成功')
                        yield put({ type: 'getDetail', payload: { id: data.id } })
                        yield put({ type: 'updateStore', payload: { actionType: 'edit' } })
                            // hashHistory.push({
                            // 	pathname:'/home/infoAdmin/liveList'
                            // })
                    }

                    // yield put({ type: 'updateStore', payload: { pageConfig: { ...pageConfig, ...payload } } })
                }

            } catch (e) {
                console.error(e)
            }
        },
        * initActivity({ payload }, { put, call, select }) {
            let liveBroadcastRelats = {
                ACTIVITY: [],
                GAME: [],
                COUPONS: [],
                SECKILL: []
            }
            yield put({ type: 'updateStore', payload: { liveBroadcastRelats } });
        },
        * handleDisabled({ payload }, { put, call, select }) {
            let { published, actionType } = payload
            yield put({ type: 'updateStore', payload: { isDisabled: (actionType == 'check' || (published == 1 && actionType == 'edit')) ? true : false } });

        }

    },

    // 存入状态机
    reducers: {
        updateStore(preState, action) {
            return Object.assign({}, preState, action.payload)
        },
    }
}

export default tmpModule
